<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}

require_once 'config.php';
require_once 'alipay.php';

$order_no = $_GET['out_trade_no'] ?? '';
$trade_status = $_GET['trade_status'] ?? '';

// 记录跳转日志
function writeLog($message) {
    $log_file = __DIR__ . '/return.log';
    $time = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$time] $message\n", FILE_APPEND | LOCK_EX);
}

writeLog("同步跳转 - 订单号: $order_no, 状态: $trade_status");

if (empty($order_no)) {
    header('Location: index.php');
    exit;
}

// 验证签名
$alipay = new AlipayF2F(
    ALIPAY_APP_ID,
    ALIPAY_PRIVATE_KEY,
    ALIPAY_PUBLIC_KEY,
    ALIPAY_NOTIFY_URL,
    ALIPAY_RETURN_URL
);

$data = $_GET;
if (!$alipay->verifyNotify($data)) {
    writeLog("签名验证失败");
    header('Location: failed.php?order_no=' . $order_no);
    exit;
}

writeLog("签名验证成功");

// 根据交易状态跳转
switch ($trade_status) {
    case 'TRADE_SUCCESS':
        // 支付成功，跳转到成功页面
        header('Location: success.php?order_no=' . $order_no);
        break;
        
    case 'TRADE_CLOSED':
        // 交易关闭，跳转到失败页面
        header('Location: failed.php?order_no=' . $order_no);
        break;
        
    case 'WAIT_BUYER_PAY':
        // 等待买家付款，跳转到支付页面
        header('Location: payment.php?order_no=' . $order_no);
        break;
        
    default:
        // 其他状态，跳转到支付页面
        header('Location: payment.php?order_no=' . $order_no);
        break;
}
?> 